/**
 * Description:
 * Class Name:GetPostTest
 * Date:2022/5/22 15:22
 *
 * @author LTisme
 * @version JAVA17
 */
package 疯狂Java讲义.第17章_网络编程._17_2_Java的基本网络支持._17_2_3_URL_URLConnection和URLPermission;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;

public class GetPostTest {
    /**
     * 向指定 URl 发送 GET 方式的请求
     * @param url 发送请求的 URL
     * @param param 请求参数，格式满足 name1=value1&name2=value2
     * @return URL 代表远程资源的响应
     */
    public static String sendGet(String url, String param){
        String result = "";
        String urlName = url + "?" + param;
        try {
            var realUrl = new URL(urlName);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.64 Safari/537.36 Edg/101.0.1210.53");
            // 建立实际连接
            connection.connect();
            // 获取所有响应头的字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
            System.out.println("下面开始遍历所有的响应头字段");
            for (var key :
                    map.keySet()) {
                System.out.println(key + "---->" + map.get(key));
            }
            System.out.println("遍历所有的响应头字段结束");
            try (
                    // 定义BufferedReader 输入流来读取URL的响应
                    var in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"))
            ) {
                String line;
                while ((line = in.readLine()) != null) {
                    result += "\n" + line;
                }
            }
        }
        catch (Exception e){
            System.out.println("发送 GET 请求出现异常！" + e);
            e.printStackTrace();
        }
        return result;
    }
    /**
     * 向指定URL发送POST方法的请求
     * @param url 发送请求的URL
     * @param param 请求参数，格式应该满足name1=value1&name2=value2的形式。
     * @return URL所代表远程资源的响应
     */
    public static String sendPost(String url, String param){
        String result = "";
        try {
            var realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.64 Safari/537.36 Edg/101.0.1210.53");
            // 发送POST请求必须设置如下两行
            connection.setDoOutput(true);
            connection.setDoInput(true);
            try (
                    // 获取URLConnection对象对应的输出流
                    var out = new PrintWriter(connection.getOutputStream())
                    ){
                // 发送请求参数
                out.print(param);
                // flush 输出流的缓冲
                out.flush();
            }
            try (
                    // 定义 BufferedReader 输入流来读取URL的响应
                    var in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"))
                    ){
                String line;
                while ((line = in.readLine()) != null){
                    result += "\n" + line;
                }
            }
        }
        catch (Exception e){
            System.out.println("发送POST请求出现异常！" + e);
            e.printStackTrace();
        }
        return result;
    }

    public static void main(String[] args) {
        String url = "https://www.baidu.com";
        // 发送GET请求
        String s = GetPostTest.sendGet(url, null);
        System.out.println(s);
        // 发送POST请求
        String s1 = GetPostTest.sendPost(url, null);
        System.out.println(s1);
    }
}
